package com.gong.gongcloudpicture1.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.gong.gongcloudpicture1.annotation.AuthCheck;
import com.gong.gongcloudpicture1.common.BaseResponse;
import com.gong.gongcloudpicture1.common.DeleteRequest;
import com.gong.gongcloudpicture1.constant.UserConstant;
import com.gong.gongcloudpicture1.exception.BusinessException;
import com.gong.gongcloudpicture1.exception.ErrorCode;
import com.gong.gongcloudpicture1.exception.ThrowUtils;
import com.gong.gongcloudpicture1.manager.CacheManager;
import com.gong.gongcloudpicture1.model.dto.picture.*;
import com.gong.gongcloudpicture1.model.entity.picture.Picture;
import com.gong.gongcloudpicture1.model.entity.user.User;
import com.gong.gongcloudpicture1.model.vo.picture.PictureTagCategory;
import com.gong.gongcloudpicture1.model.vo.picture.PictureVO;
import com.gong.gongcloudpicture1.model.vo.user.UserLoginVo;
import com.gong.gongcloudpicture1.service.PictureService;
import com.gong.gongcloudpicture1.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;


/**
 * 图片控制层
 */
@Slf4j
@RestController
@RequestMapping("/picture")
public class PictureController {


    @Resource
    private PictureService pictureService;

    @Resource
    private UserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 文件上传
     *
     * @param multipartFile
     * @param pictureUploadRequest
     * @param request
     * @return
     */
    @PostMapping("/upload")
    @AuthCheck(mastRole = UserConstant.ADMIN)
    public BaseResponse<PictureVO> uploadPicture(@RequestPart("file") MultipartFile multipartFile, PictureUploadRequest pictureUploadRequest, HttpServletRequest request) {
        User userLoginVo = userService.getLogInUser2(request);
        return pictureService.uploadPicture(multipartFile, pictureUploadRequest, userLoginVo);
    }


    /**
     * 文件地址上传
     *
     * @param pictureUploadRequest
     * @param request
     * @return
     */
    @PostMapping("/upload/url")
    @AuthCheck(mastRole = UserConstant.ADMIN)
    public BaseResponse<PictureVO> uploadPictureByUrl(@RequestBody PictureUploadRequest pictureUploadRequest, HttpServletRequest request) {
        User userLoginVo = userService.getLogInUser2(request);
        return pictureService.uploadPicture(pictureUploadRequest.getFileUrl(), pictureUploadRequest, userLoginVo);
    }


    /**
     * 图片分页(用户使用)
     *
     * @param pictureQueryRequest
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<PictureVO>> listPictureVoByPage(@RequestBody PictureQueryRequest pictureQueryRequest) {
        ThrowUtils.throwIf(pictureQueryRequest == null, new BusinessException(ErrorCode.PARAMS_ERROR));
        //限制爬虫, 防止用户查询更多数据
        ThrowUtils.throwIf(pictureQueryRequest.getPageSize() > 20, new BusinessException(ErrorCode.PARAMS_ERROR));
        return BaseResponse.success(pictureService.listPictureVoByPage(pictureQueryRequest));
    }


    /**
     * 图片分页(用户使用) - redis缓存
     *
     * @param pictureQueryRequest
     * @return
     */
    @PostMapping("/list/page/vo/cache")
    public BaseResponse<Page<PictureVO>> listPictureVoByPageWithCache(@RequestBody PictureQueryRequest pictureQueryRequest) {
        ThrowUtils.throwIf(pictureQueryRequest == null, new BusinessException(ErrorCode.PARAMS_ERROR));
        //限制爬虫, 防止用户查询更多数据
        ThrowUtils.throwIf(pictureQueryRequest.getPageSize() > 20, new BusinessException(ErrorCode.PARAMS_ERROR));

        //先查询缓存, 如果缓存中没有则查数据库, 然后再将数据缓存到redis中
        //将查询体转成JSON字符串
        String queryCondition = JSONUtil.toJsonStr(pictureQueryRequest);
        //将查询体通过MD5hash算法来来压缩
        String hashKey = DigestUtils.md5DigestAsHex(queryCondition.getBytes());
        //构建缓存key key设计的基本规则 项目名称:方法名:${查询条件key}
        String redisKey = "picture:listPictureVoByPage:" + hashKey;
        //得到redis操作对象
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        //从redis中进行查询 得到结果
        //String cachedValue = opsForValue.get(redisKey);
        /**
         * 多级缓存代码改造
         */
        Page<PictureVO> value = (Page) CacheManager.getValue(redisKey, Page.class);
        if (value != null) {
            return BaseResponse.success(value);
        }
        //如果都没有命中, 则将查询到的数据缓存到redis和本地缓存中
        Page<PictureVO> pictureVOPage = pictureService.listPictureVoByPage(pictureQueryRequest);
        String cacheValue = JSONUtil.toJsonStr(pictureVOPage);
        /**
         * 设置缓存时间为 5 - 10 分钟
         * 单位: 秒
         * 为了防止缓存雪崩的问题, 将过期时间随机化, 如果都设置了统一的时间, 那么key就会在同一时间内同时过期, 大量请求落入数据库, 可能会导致数据库崩溃
         */
        //定义缓存时间
        int cacheExpireTime = 300 + RandomUtil.randomInt(0, 300);
        CacheManager.setValue(redisKey, cacheValue, cacheExpireTime, TimeUnit.SECONDS);
        return BaseResponse.success(pictureVOPage);
    }


    /**
     * 删除图片
     *
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deletePicture(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //判断是否存在
        Picture picture = pictureService.getById(deleteRequest.getId());
        ThrowUtils.throwIf(picture == null, new BusinessException(ErrorCode.NOT_FOUND_ERROR));
        //只有本人和管理员才能删除
        UserLoginVo userLoginVo = userService.getLogInUser(request).getData();
        if (!userLoginVo.getUserRole().equals(UserConstant.ADMIN) || !userLoginVo.getId().equals(picture.getUserId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "只有管理员和创作者可以删除");
        }
        //操作数据库
        boolean result = pictureService.removeById(picture.getId());
        ThrowUtils.throwIf(!result, new BusinessException(ErrorCode.OPERATION_ERROR, "数据库错误"));
        return BaseResponse.success(result);
    }


    /**
     * 更新图片(仅管理员使用)
     *
     * @param pictureUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mastRole = UserConstant.ADMIN)
    public BaseResponse<Boolean> updatePicture(@RequestBody PictureUpdateRequest pictureUpdateRequest, HttpServletRequest request) {
        if (pictureUpdateRequest == null || pictureUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //判断愿数据是否存在
        Picture picture = pictureService.getById(pictureUpdateRequest.getId());
        ThrowUtils.throwIf(picture == null, new BusinessException(ErrorCode.NOT_FOUND_ERROR));
        //更新
        BeanUtils.copyProperties(pictureUpdateRequest, picture);
        picture.setTags(JSONUtil.toJsonStr(pictureUpdateRequest.getTags()));
        User user = userService.getLogInUser2(request);
        pictureService.fillReviewStatus(picture, user);
        pictureService.validPicture(picture);
        //操作数据库
        boolean result = pictureService.updateById(picture);
        ThrowUtils.throwIf(!result, new BusinessException(ErrorCode.SYSTEM_ERROR, "数据库错误!"));
        return BaseResponse.success(result);
    }


    /**
     * 根据id获取图片(仅管理员使用)
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get")
    @AuthCheck(mastRole = UserConstant.ADMIN)
    public BaseResponse<Picture> getPictureById(Long id, HttpServletRequest request) {
        if (id == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (pictureService.getById(id) == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return BaseResponse.success(pictureService.getById(id));
    }


    /**
     * 根据id获取图片封装类
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<PictureVO> getPictureVoById(Long id, HttpServletRequest request) {
        if (id == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Picture picture = pictureService.getById(id);
        if (picture == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        PictureVO pictureVO = pictureService.getPictureVO(picture);
        return BaseResponse.success(pictureVO);
    }


    /**
     * 获取图片管理分页(管理员使用)
     *
     * @param pictureQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mastRole = UserConstant.ADMIN)
    public BaseResponse<Page<Picture>> getPictureByPage(@RequestBody PictureQueryRequest pictureQueryRequest) {
        Page<Picture> page = pictureService.page(new Page<>(pictureQueryRequest.getCurrent(), pictureQueryRequest.getPageSize()), pictureService.getQueryWrapper(pictureQueryRequest));
        return BaseResponse.success(page);
    }


    /**
     * 编辑图片(用户使用)
     *
     * @param pictureEditRequest
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editPicture(@RequestBody PictureEditRequest pictureEditRequest, HttpServletRequest request) {
        if (pictureEditRequest == null || pictureEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //判断原数据是否存在
        Picture picture = pictureService.getById(pictureEditRequest.getId());
        if (picture == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //判断用户是否登录
        User user = userService.getLogInUser2(request);
        //判断当前图片的创作者是否是当前用户本人, 或者是管理员
        Long pictureUserId = picture.getUserId();
        Long userId = user.getId();
        if (!pictureUserId.equals(userId) && !user.getUserRole().equals(UserConstant.ADMIN)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "仅管理员和当前图片的创作者可以修改!");
        }
        //更新数据
        picture.setName(pictureEditRequest.getName());
        picture.setIntroduction(pictureEditRequest.getIntroduction());
        picture.setCategory(pictureEditRequest.getCategory());
        picture.setTags(JSONUtil.toJsonStr(pictureEditRequest.getTags()));
        pictureService.fillReviewStatus(picture, user);
        boolean result = pictureService.updateById(picture);
        ThrowUtils.throwIf(!result, new BusinessException(ErrorCode.OPERATION_ERROR, "数据库错误"));
        return BaseResponse.success(true);
    }


    /**
     * 前端默认标签和分类
     *
     * @return
     */
    @GetMapping("/tag_category")
    public BaseResponse<PictureTagCategory> listPictureTagCategory() {
        PictureTagCategory pictureTagCategory = new PictureTagCategory();
        List<String> tagList = Arrays.asList("热门", "搞笑", "生活", "高清", "艺术", "校园", "背景", "简历", "创意");
        List<String> categoryList = Arrays.asList("模板", "电商", "表情包", "素材", "海报");
        pictureTagCategory.setTagList(tagList);
        pictureTagCategory.setCategoryList(categoryList);
        return BaseResponse.success(pictureTagCategory);
    }


    /**
     * 图片审核 管理员使用
     *
     * @param pictureReviewRequest
     * @param request
     * @return
     */
    @PostMapping("/review")
    @AuthCheck(mastRole = UserConstant.ADMIN)
    public BaseResponse<Boolean> doPictureReview(PictureReviewRequest pictureReviewRequest, HttpServletRequest request) {
        pictureService.doPictureReview(pictureReviewRequest, request);
        return BaseResponse.success(true);
    }


    /**
     * 批量抓取图片并上传 - 管理员使用
     *
     * @param pictureUploadByBatchRequest
     * @param request
     * @return
     */
    @PostMapping("/upload/batch")
    @AuthCheck(mastRole = UserConstant.ADMIN)
    public BaseResponse<Integer> uploadPictureByBatch(@RequestBody PictureUploadByBatchRequest pictureUploadByBatchRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(pictureUploadByBatchRequest == null, ErrorCode.PARAMS_ERROR);
        User user = userService.getLogInUser2(request);
        Integer count = pictureService.uploadPictureByBatch(pictureUploadByBatchRequest, user);
        return BaseResponse.success(count);
    }


}
